package com.leyou.filter;

import java.io.*;
import java.security.*;
import javax.crypto.*;
import org.apache.commons.codec.binary.Base64;
 
public class KeyGenerator {
    public static void main(String[] args) throws Exception {
        // 创建KeyPairGenerator对象
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        
        // 初始化KeyPairGenerator
        SecureRandom secureRandom = new SecureRandom();
        keyGen.initialize(2048, secureRandom);
        
        // 生成密钥对
        KeyPair pair = keyGen.generateKeyPair();
        
        // 获取公钥和私钥
        PublicKey publicKey = pair.getPublic();
        PrivateKey privateKey = pair.getPrivate();
        
        // 转换为PEM格式字符串
        String publicPem = convertToPemFormat(publicKey);
        String privatePem = convertToPemFormat(privateKey);
        
        System.out.println("公钥:\n" + publicPem);
        System.out.println("\n私钥:\n" + privatePem);
    }
    
    private static String convertToPemFormat(Key key) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
        objectOutputStream.writeObject(key);
        byte[] bytes = Base64.encodeBase64(outputStream.toByteArray());
        return "-----BEGIN PUBLIC KEY-----\n" + new String(bytes) + "\n-----END PUBLIC KEY-----";
    }
}